package com.neusoft.nep.NEPG.controller;

import com.neusoft.nep.entity.Gridder;
import com.neusoft.nep.entity.nepgResult;
import com.neusoft.nep.entity.nepsFeedback;
import com.neusoft.tools.FileUtils;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.neusoft.tools.Constants.*;
import static com.neusoft.tools.AlertUtils.showDialog;
import static com.neusoft.tools.FileUtils.*;

public class FeedbackInfoViewController {
    @FXML
    private Label userInformation;
    @FXML
    private Label locations;
    @FXML
    private Label address;
    @FXML
    private Label level;
    @FXML
    private Label status;
    @FXML
    private Label AQIResContent;
    @FXML
    private TextField so2;
    @FXML
    private TextField pm25;
    @FXML
    private TextField co;
    @FXML
    private Button commit;
    @FXML
    private Label so2Level;
    @FXML
    private Label coLevel;
    @FXML
    private Label pm25Level;

    private String realLevel;

    private nepsFeedback feedback;

    private Gridder gridder;

    private TextFormatter<Integer> createIntegerFormatter() {
        return new TextFormatter<>(change -> {
            String newText = change.getControlNewText();
            if (newText.matches("\\d*")) {
                return change;
            }
            return null;
        });
    }



    public void initial(nepsFeedback feedbacks, Gridder gridder) {
        this.feedback = feedbacks;
        this.gridder = gridder;
        this.userInformation.setText(" " + feedback.getUsername() + " " + feedback.getPhoneNumber());
        this.locations.setText(" " + feedback.getProvince() + " " + feedback.getCity());
        this.address.setText(" " + feedback.getAddress());
        this.level.setText(" " + feedback.getLevel());
        this.status.setText(" " + feedback.getContent());

        so2.setTextFormatter(createIntegerFormatter());
        so2.textProperty().addListener((observable, oldValue, newValue) -> {
            so2Level.setText(SO2_TO_AQI_LEVEL(Integer.parseInt(newValue)));
        });

        pm25.setTextFormatter(createIntegerFormatter());
        pm25.textProperty().addListener((observable, oldValue, newValue) -> {
            pm25Level.setText(PM25_TO_AQI_LEVEL(Integer.parseInt(newValue)));
        });

        co.setTextFormatter(createIntegerFormatter());
        co.textProperty().addListener((observable, oldValue, newValue) -> {
            coLevel.setText(CO_TO_AQI_LEVEL(Integer.parseInt(newValue)));
        });

       so2Level.textProperty().addListener((observable, oldValue, newValue) -> updateRealLevel());
       coLevel.textProperty().addListener((observable, oldValue, newValue) -> updateRealLevel());
       pm25Level.textProperty().addListener((observable, oldValue, newValue) -> updateRealLevel());
    }

    private void updateRealLevel() {

        Integer val1 = CHARACTER_SWITCH_VALUE.get(so2Level.getText());
        Integer val2 = CHARACTER_SWITCH_VALUE.get(pm25Level.getText());
        Integer val3 = CHARACTER_SWITCH_VALUE.get(coLevel.getText());

        int v1 = (val1 != null) ? val1 : 0;
        int v2 = (val2 != null) ? val2 : 0;
        int v3 = (val3 != null) ? val3 : 0;

        int maxVal = Math.max(v1, Math.max(v2, v3));

        this.realLevel = VALUE_SWITCH_CHARACTER.getOrDefault(maxVal, "错误");

        String description = POLLUTION_LEVEL_DESCRIPTION.getOrDefault(this.realLevel, "出现了未定义的数据");
        AQIResContent.setText("实测AQI等级：" + this.realLevel + " " + description);
    }

    public void commit() throws IOException {
        if (so2.getText().isEmpty() || pm25.getText().isEmpty() || co.getText().isEmpty()) {
            showDialog("error", "请填写所有监测数据！");
            return;
        }

        int s1 = Integer.parseInt(so2.getText());
        int s2 = Integer.parseInt(pm25.getText());
        int s3 = Integer.parseInt(co.getText());

        if (s1 < 0 || s1 > 10000) {
            showDialog("error", "so2数值应在 0 到 10000 之间！");
            return;
        }
        if( s2 < 0 || s2 > 500) {
            showDialog("error", "co数值应在 0 到 500 之间！");
            return;
        }
        if(s3 < 0 || s3 > 500) {
            showDialog("error", "pm2.5数值应在 0 到 500 之间！");
            return;
        }

        String filename = "NEPGworks.txt";
        String resName = "NEPGresult.txt";
        List<nepgResult> finalDataList = readListObject(resName);
        //将处理过的反馈归档
        nepgResult res = new nepgResult(feedback.getProvince(), feedback.getCity(), feedback.getAddress(), gridder.getUsername(), gridder.getPhone(), feedback.getDate(), s1, s3, s2, realLevel);
        finalDataList.add(res);
        writeListObject(resName, finalDataList);
        //删除处理过的反馈
        Map<String, List<nepsFeedback> > nepgFeedbackMap = readMapObject(filename);
        List<nepsFeedback> feedbackList = nepgFeedbackMap.get(gridder.getIdAsString());
        feedbackList.remove(feedback);
        nepgFeedbackMap.put(gridder.getIdAsString(), feedbackList);
        writeMapObject(filename, nepgFeedbackMap);
        showDialog("success","commit success!");

        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/FeedbackListView.fxml"));
            Parent root = (Parent) fxmlLoader.load();
            Scene scene = new Scene(root);
            Stage stage = (Stage) this.commit.getScene().getRoot().getScene().getWindow();
            FeedbackListViewController controller = fxmlLoader.getController();
            controller.initGridder(gridder);
            stage.setScene(scene);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
